<?php

  include "auth.php";
  include "counter.php";

  function create_report() {
    $MIN_SLOT_SIZE = 60;
    
    $counters = array();
    
    $read_from = log_file_path();
    if (isset($_POST["production_call"]) and file_exists($read_from)) {
      rename($read_from, $read_from.".export");
      $read_from .= ".export";
    }
    
    $handle = @fopen($read_from, "r");
    if ($handle) {
      while (($buffer = fgets($handle, 4096)) !== false) {
        $parts = explode(" ", trim($buffer), 3);
        $epoch = (int) $parts[0];
        $delta = $parts[1];
        $name = $parts[2];
  
        if (!isset($counters[$name])) {
          $counters[$name] = array();
        }
        
        $epoch -= $epoch % 60;
        if (!isset($counters[$name][$epoch])) {
          $counters[$name][$epoch] = 0;
        }
        $counters[$name][$epoch] += $delta;
      }
      fclose($handle);
      if (isset($_POST["production_call"])) {
        unlink($read_from);
      }
    }
    $result = array("time" => time(), "counters" => $counters);
    if (isset($_GET["json"]) or isset($_POST["production_call"])) {
      echo json_encode($result);
    } else {
      echo "<h3>Data since last export:</h3>";
      foreach($counters as $key => $value) {
        echo "<b>$key</b>: ".array_sum($value)."<br>";
      }
      echo "<br>";
      echo "<a href='http://www.prodeagle.com'>Go to ProdEagle dashboard</a>";
    }
  }
  
  if (auth()) {
    if (isset($_GET["administrator"]) or isset($_GET["viewer"])) {
      add_user();
    } else {
      create_report();
    }
  }
  
?>
